package com.web.exiaodao.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Function;
import com.web.exiaodao.business.entity.User;
import com.web.exiaodao.business.entity.WalletRechargeRecord;
import com.web.exiaodao.business.repository.UserRepository;
import com.web.exiaodao.business.repository.WalletRechargeRecordRepository;
import com.web.exiaodao.business.service.WalletRechargeRecordService;
import com.web.exiaodao.remote.vo.WalletRechargeRecordVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service("WalletRechargeRecordService")
@Transactional(readOnly = false)
public class WalletRechargeRecordServiceImpl extends BaseService<WalletRechargeRecordVo> implements WalletRechargeRecordService {

    private static final Logger LOGGER = Logger.getLogger(WalletRechargeRecordServiceImpl.class);

    @Autowired
    private WalletRechargeRecordRepository walletRechargeRecordRepository;
    @Autowired
    private UserRepository userRepository;

    /**
     * 查询单条WalletRechargeRecord信息
     * //@param tId
     *
     * @return 返回单个WalletRechargeRecord对象
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<WalletRechargeRecordVo> findOne(Long modelId) throws BusinessException {
        WalletRechargeRecord obj = new WalletRechargeRecord();
        if (modelId != 0) {
            obj = walletRechargeRecordRepository.findByIdAndStatusNot(modelId, XaConstant.Status.delete);
        }
        XaResult<WalletRechargeRecordVo> xr = new XaResult<WalletRechargeRecordVo>();
        if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), WalletRechargeRecordVo.class));
            LOGGER.info("后台----->查询单个实体----->WalletRechargeRecordVo");
        } else {
            xr.error(XaConstant.Message.object_not_find);
            LOGGER.info(XaConstant.Message.object_not_find);
        }
        return xr;
    }

    /**
     * 分页查询状态非status的WalletRechargeRecord数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象WalletRechargeRecord集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<WalletRechargeRecordVo>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示非删除的所有数据
            status = XaConstant.Status.delete;
        }
        filters.put("status", new SearchFilter("status", Operator.NE, status));
        Page<WalletRechargeRecord> page = walletRechargeRecordRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), WalletRechargeRecord.class), pageable);
        XaResult<Page<WalletRechargeRecordVo>> xr = new XaResult<>();
        xr.setObject(new MyPage<>(page, JSON.parseArray(JSON.toJSONString(page.getContent()), WalletRechargeRecordVo.class)));

        //查询用户信息
        if (page.getContent().size() > 0) {
            List<Long> userIdLongs     = com.web.webstart.base.util.CollectionUtils.subCollection(page.getContent(), "userId");
            Iterable<User> userIterable =  userRepository.findAll(userIdLongs);
            Map<Long,User> userMap = com.web.webstart.base.util.CollectionUtils.listToMap(userIterable.iterator(), new Function<User, Long>() {
                @Override
                public Long apply(User user) {
                    return user.getId();
                }
            });
            for (int i = 0; i < xr.getObject().getContent().size(); ++i) {
                WalletRechargeRecordVo vo = xr.getObject().getContent().get(i);
                User userTemp = userMap.get(vo.getUserId());
                xr.getObject().getContent().get(i).setUser(userTemp);
            }
        }

        LOGGER.info("后台----->分页查询实体集合（状态不等于）----->WalletRechargeRecordVo");
        return xr;
    }

    /**
     * 分页查询状态status的WalletRechargeRecord数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象WalletRechargeRecord集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<WalletRechargeRecordVo>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", Operator.EQ, status));
        Page<WalletRechargeRecord> page = walletRechargeRecordRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), WalletRechargeRecord.class), pageable);
        XaResult<Page<WalletRechargeRecordVo>> xr = new XaResult<Page<WalletRechargeRecordVo>>();
        xr.setObject(new MyPage<>(page, JSON.parseArray(JSON.toJSONString(page.getContent()), WalletRechargeRecordVo.class)));
        LOGGER.info("后台----->分页查询实体集合（状态等于）----->WalletRechargeRecordVo");
        return xr;
    }

    /**
     * 保存WalletRechargeRecord信息
     *
     * @param model
     * @return
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<WalletRechargeRecordVo> saveOrUpdate(WalletRechargeRecordVo model) throws BusinessException {
        WalletRechargeRecord obj = null;
        if (XaUtil.isNotEmpty(model.getId())) {
            obj = walletRechargeRecordRepository.findOne(model.getId());
        } else {
            obj = new WalletRechargeRecord();
        }
        obj.setCreateUser(XaUtil.isNotEmpty(model.getCreateUser()) ? model.getCreateUser() : obj.getCreateUser());
        obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
        obj.setRechargeMoney(XaUtil.isNotEmpty(model.getRechargeMoney()) ? model.getRechargeMoney() : obj.getRechargeMoney());
        obj.setRechargeOrderNo(XaUtil.isNotEmpty(model.getRechargeOrderNo()) ? model.getRechargeOrderNo() : obj.getRechargeOrderNo());
        obj.setRechargeMethod(XaUtil.isNotEmpty(model.getRechargeMethod()) ? model.getRechargeMethod() : obj.getRechargeMethod());
        obj.setRechargeStatus(XaUtil.isNotEmpty(model.getRechargeStatus()) ? model.getRechargeStatus() : obj.getRechargeStatus());
        obj.setQueryId(XaUtil.isNotEmpty(model.getQueryId()) ? model.getQueryId() : obj.getQueryId());
        obj.setOrderPayDateTime(XaUtil.isNotEmpty(model.getOrderPayDateTime()) ? model.getOrderPayDateTime() : obj.getOrderPayDateTime());
        obj = walletRechargeRecordRepository.save(obj);
        XaResult<WalletRechargeRecordVo> xr = new XaResult<WalletRechargeRecordVo>();
        xr.setObject(JSON.parseObject(JSON.toJSONString(obj), WalletRechargeRecordVo.class));
        LOGGER.info("后台新增或编辑数据成功！");
        return xr;
    }

    /**
     * 修改WalletRechargeRecord状态，可一次修改多条   3删除  -1锁定  1正常
     * //@param userId
     *
     * @param modelIds
     * @param status
     * @return 返回WalletRechargeRecord对象
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<WalletRechargeRecordVo> multiOperate(
            String modelIds, Integer status) throws BusinessException {
        XaResult<WalletRechargeRecordVo> xr = new XaResult<WalletRechargeRecordVo>();
        if (status == null) {
            status = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                WalletRechargeRecord obj = walletRechargeRecordRepository.findByIdAndStatusNot(Long.parseLong(id), status);
                if (XaUtil.isNotEmpty(obj)) {
                    obj.setStatus(status);
                    obj = walletRechargeRecordRepository.save(obj);
                }
            }
        }
        LOGGER.info("批量修改数据状态成功！");
        return xr;
    }

}
